package com.module.overview.ui.cardHistoryDetails.provider

import android.util.Log
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.groupSleepDataByQualityAndTime
import com.module.ble.widget.CusPieChartView
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/11
 *
 * 描述：睡眠总时长卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSleepTotalDurationCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SLEEP_TOTAL_DURATION,
    override val layoutId: Int = R.layout.overview_sleep_total_duration_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    var totalDuration = 0L//睡眠总时长，单位：分钟

    var awakeDuration = 0//清醒时长，单位：分钟
    var lightDuration = 0//浅睡时长，单位：分钟
    var remDuration = 0//快速眼动时长，单位：分钟
    var deepDuration = 0//深睡时长，单位：分钟
    var napDuration = 0//小睡时长，单位：分钟

    var nightList = mutableListOf<UserSleepInfo>()
    var napList = mutableListOf<UserSleepInfo>()

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        val sleepGoalValue = SpUtilsManagement.getInt(KeyPre.KEY_SLEEP_GOALS_VALUE, 360)
        helper.setText(R.id.tvAverageHrUnit," ${getString(R.string.common_delimiter_unit)} ${TimeUtils.formatTime((sleepGoalValue * 60 * 1000L), showHour = true, showMin = true)}")

        val pieChartView = helper.getView<CusPieChartView>(R.id.pieChartView)

        // 自定义圆环宽度
        pieChartView.setStrokeWidth(ViewUtils.dp2px(132f))

        // 设置起始角度（从顶部开始）
        pieChartView.setStartAngle(-90f)

//        // 设置背景圆环颜色
//        pieChartView.setBackgroundColor(Color.parseColor("#F0F0F0"))

        doOnIOThread {
            val timeTemp = TimeUtils.getTimeRangeForSleep(curTime)

            SleepInfoRepo.instance.findByTimestampSameDayWithNapSleep(curTime).let { listIt ->
                napDuration = 0
                listIt.isNullOrEmpty().no {
                    napList.clear()
                    napList.addAll(listIt as MutableList<UserSleepInfo>)
                    listIt.forEach{
                        napDuration += (it.endTime-it.createdTime).toInt() / (1000 * 60)//转为分钟单位
                    }
                }

                SleepInfoRepo.instance.findByTimeRangeByNight(timeTemp.first, timeTemp.second)?.let { listIt->
                    listIt.sortedBy { it.createdTime }//按时间排序（升序）
                    initClassDuration()
                    nightList.clear()
                    nightList.addAll(listIt as MutableList<UserSleepInfo>)

                    if (listIt.isNotEmpty()) {
                        val nightSleepList = groupSleepDataByQualityAndTime(listIt)
                        nightSleepList.forEach {sleepDataIt->
                            totalDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
                            when (sleepDataIt.status) {// 睡眠质量 0,清醒(离床) 1:快速眼动 2:浅睡 3:深睡 4:未佩戴  101:小睡（自用） -999：未知（自用）
                                0 -> awakeDuration += sleepDataIt.timeLong  // 清醒
                                1 -> remDuration += sleepDataIt.timeLong    // 快速眼动
                                2 -> lightDuration += sleepDataIt.timeLong  // 浅睡
                                3 -> deepDuration += sleepDataIt.timeLong   // 深睡
                            }
                        }
                    }

                    doOnUiThread {
                        constructPiChartData(pieChartView)
                        helper.setText(R.id.tvTotalDuration, TimeUtils.formatTime(((napDuration+totalDuration)*60*1000), showHour = true, showMin = true))
                    }
                }
            }
        }
    }

    fun initClassDuration(){
        totalDuration = 0L//睡眠总时长，单位：分钟
        awakeDuration = 0//清醒时长，单位：分钟
        lightDuration = 0//浅睡时长，单位：分钟
        remDuration = 0//快速眼动时长，单位：分钟
        deepDuration = 0//深睡时长，单位：分钟
    }

    private fun constructPiChartData(pieChartView:CusPieChartView){

        // 创建比例数据
        val chartData = mutableListOf<CusChartData>()

        doOnIOThread {
            // 计算总时长（小睡时长 + 夜间睡眠总时长）
            val totalSleepDuration = napDuration + totalDuration

            // 如果总时长为0，则不显示饼图
            if (totalSleepDuration <= 0) {
                pieChartView.setData(emptyList())
                return@doOnIOThread
            }

            // 计算各个阶段的比例
            val deepProportion = (deepDuration.toFloat() / totalSleepDuration) * 100f
            val lightProportion = (lightDuration.toFloat() / totalSleepDuration) * 100f
            val remProportion = (remDuration.toFloat() / totalSleepDuration) * 100f
            val awakeProportion = (awakeDuration.toFloat() / totalSleepDuration) * 100f
            val napProportion = (napDuration.toFloat() / totalSleepDuration) * 100f


            // 只添加有数据的项目到饼图中
            if (deepProportion > 0) {
                chartData.add(CusChartData(//深睡
                    createdTime = System.currentTimeMillis(),
                    mColor = ViewUtils.getColor(R.color.c_6666cc),
                    mProportion = deepProportion
                ))
            }

            if (lightProportion > 0) {
                chartData.add(CusChartData(//浅睡
                    createdTime = System.currentTimeMillis(),
                    mColor = ViewUtils.getColor(R.color.c_9966ff),
                    mProportion = lightProportion
                ))
            }

            if (remProportion > 0) {
                chartData.add(CusChartData(//快速眼动
                    createdTime = System.currentTimeMillis(),
                    mColor = ViewUtils.getColor(R.color.c_cc99ff),
                    mProportion = remProportion
                ))
            }

            if (awakeProportion > 0) {
                chartData.add(CusChartData(//清醒
                    createdTime = System.currentTimeMillis(),
                    mColor = ViewUtils.getColor(R.color.c_ffbfff),
                    mProportion = awakeProportion
                ))
            }

            if (napProportion > 0) {
                chartData.add(CusChartData(//小睡
                    createdTime = System.currentTimeMillis(),
                    mColor = ViewUtils.getColor(R.color.c_ff8a06),
                    mProportion = napProportion
                ))
            }
        }

        // 设置数据
        pieChartView.setData(chartData)
    }
}